package bean.managed;

import entity.SalesOrderEntity;
import bean.managed.util.JsfUtil;
import bean.session.SalesOrderEntityFacade;

import entity.AddressEntity;
import entity.BillingRequestEntity;
import entity.CustomerAccountEntity;
import entity.CustomerEntity;
import entity.CustomerInvoiceEntity;
import entity.DepartmentEntity;
import entity.PackingOrderEntity;
import entity.RefundRequestEntity;
import entity.ReservationEntity;
import entity.SalesLeadEntity;
import entity.ShippingOrderEntity;
import entity.ShippingRequestEntity;
import entity.SystemUserEntity;
import exception.CustomerAccountDoesNotExistException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import type.InternalStatus;
import type.InvoiceStatus;
import type.InvoiceType;
import type.PackingOrderStatus;
import type.RefundRequestStatus;
import type.SalesOrderStatus;
import type.ShippingOrderStatus;
import util.Fixtures.Department;

@ManagedBean(name = "salesOrderEntityController")
@SessionScoped
public class SalesOrderEntityController extends AbstractBacking implements Serializable {

    private int reservedNutriBarNuts;
    private int reservedNutriBarFruits;
    private int reservedPremiumPowerBarNuts;
    private int reservedPremiumPowerBarFruits;
    private SalesOrderEntity current;
    private DataModel items = null;
    private DataModel searchItems = null;
    @EJB
    private bean.session.SalesOrderEntityFacade ejbFacade;
    @EJB
    private bean.session.ShippingOrderEntityFacade shippingOrderFacade;
    @EJB
    private bean.session.ShippingRequestEntityFacade shippingRequestFacade;
    @EJB
    private bean.session.CustomerAccountEntityFacade customerAccountFacade;
    @EJB
    private bean.session.BillingRequestEntityFacade billingRequestFacade;
    @EJB
    private bean.session.DepartmentEntityFacade departmentFacade;
    @EJB
    private bean.session.RefundRequestEntityFacade refundRequestFacade;
    private PurchaseOrderEntityController purchaseOrderEntityController;
    private CustomerEntityController customerEntityController;
    private String attribute = "id";
    private String input;
    @ManagedProperty(value = "#{systemMessageController}")
    private SystemMessageController systemMessageController;
    private String note;

    public SalesOrderEntityController() {
    }

    public SalesOrderEntityFacade getEjbFacade() {
        return ejbFacade;
    }

    public void setEjbFacade(SalesOrderEntityFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }

    public boolean checkSystemUser() {
        if (getCurrentUser() instanceof SystemUserEntity) {
            return true;
        }
        return false;
    }

    public boolean checkSalesLead() {
        if (getLoginSalesLead() instanceof SalesLeadEntity) {
            return true;
        }
        return false;
    }

    public boolean checkCustomer() {
        if (getLoginCustomer() instanceof CustomerEntity) {
            return true;
        }
        return false;
    }

    public SalesOrderEntity getSelected() {
        if (current == null) {
            current = new SalesOrderEntity();
        }else if(current.getId()!=null){
            current = ejbFacade.find(current.getId());
        }
        return current;
    }

    private SalesOrderEntityFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        recreateModel();
        return "/entities/salesOrderEntity/List?faces-redirect=true";
    }

    public String prepareEdit() {
        current = (SalesOrderEntity) getItems().getRowData();
        purchaseOrderEntityController.setSelected(current.getPurchaseOrder());
        return "/entities/salesOrderEntity/Edit?faces-redirect=true";
    }

    public String prepareView() {
        current = (SalesOrderEntity) getItems().getRowData();
        purchaseOrderEntityController.setSelected(current.getPurchaseOrder());
        return "/entities/salesOrderEntity/View?faces-redirect=true";
    }

    public String prepareCreate() {
        current = new SalesOrderEntity();
        return "/entities/salesOrderEntity/Create?faces-redirect=true";
    }

    public String prepareSearch() {
        setSearchItems(getSearchItems());
        return "/entities/salesOrderEntity/SearchList?faces-redirect=true";
    }

    public DataModel getSearchItems() {
        if (getAttribute().equals("id")) {
            searchItems = ejbFacade.searchSalesOrderById(getAttribute(), getInput());
        } else if (getAttribute().equals("Name")) {
            searchItems = ejbFacade.searchSalesOrderByName(getAttribute(), getInput());
        }
        items = searchItems;
        return searchItems;
    }

    public String create() {
        try {
            if (current.getCustomer().isBlackListed()) {
                throw new Exception("Customer is Blacklisted. Advise customer to clear outstanding payments.");
            } else {
                current.created(getLoginPerson());
                getFacade().create(current);
//                purchaseOrderEntityController.getSelected().setSalesOrder(current);
//                purchaseOrderEntityController.update();
//                purchaseOrderEntityController.prepareList();
                SystemUserEntity salesManager = getFacade().getManagerFromDept(Department.Sales.getName());
                //SystemUserEntity productionManager = getFacade().getManagerFromDept(Department.ProductionPlanning.getName());
                systemMessageController.getEjbFacade().createAndSendSystemMessage(salesManager,
                        current.getCustomer().getFullname() + " created Sales Order # " + current.getId() + ".",
                        "/index", systemMessageController);
            }
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesOrderEntityCreated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String update() {
        try {
            current.modified(getLoginPerson());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesOrderEntityUpdated"));
            return "/entities/salesOrderEntity/View.xhtml";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (SalesOrderEntity) getItems().getRowData();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        return "List";
    }

    private void performDestroy() {
        try {
            current.modified(getLoginPerson());
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesOrderEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            if (getLoginPerson() instanceof SystemUserEntity) {
                items = getFacade().getAllSalesOrder();
            } else if (getLoginPerson() instanceof CustomerEntity) {
                items = getFacade().getAllSalesOrderForCustomer(getLoginPerson().getId());
            }
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public PurchaseOrderEntityController getPurchaseOrderEntityController() {
        return purchaseOrderEntityController;
    }

    public void setPurchaseOrderEntityController(PurchaseOrderEntityController purchaseOrderEntityController) {
        this.purchaseOrderEntityController = purchaseOrderEntityController;
    }

    public CustomerEntityController getCustomerEntityController() {
        return customerEntityController;
    }

    public void setCustomerEntityController(CustomerEntityController customerEntityController) {
        this.customerEntityController = customerEntityController;
    }

    public void setSearchItems(DataModel searchItems) {
        this.searchItems = searchItems;
    }

    public String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public SystemMessageController getSystemMessageController() {
        return systemMessageController;
    }

    public void setSystemMessageController(SystemMessageController systemMessageController) {
        this.systemMessageController = systemMessageController;
    }

    @FacesConverter(forClass = SalesOrderEntity.class)
    public static class SalesOrderEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            SalesOrderEntityController controller = (SalesOrderEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "salesOrderEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof SalesOrderEntity) {
                SalesOrderEntity o = (SalesOrderEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + SalesOrderEntityController.class.getName());
            }
        }
    }

    public String confirmSO() {
        current.setStatus(SalesOrderStatus.Confirmed);
        DepartmentEntity productionDp = departmentFacade.findDepartmentByName(Department.ProductionPlanning.getName());
        SystemUserEntity productionManager = productionDp.getManager();
        String message = "Sales Order with ID " + current.getId() + " is confirmed. Please approve the relevant back orders for it.";

        systemMessageController.getEjbFacade().createAndSendSystemMessage(productionManager,
                message, "/entities/backOrderEntity/List.xhtml", systemMessageController);
        current.setInternalStatus(InternalStatus.DeliveryPending);
        update();
        return "View";
    }

    public String cancelSO() {
        current.setStatus(SalesOrderStatus.Cancelled);
        refundCreditPayable(true);
        cancelAllReservations();
        getFacade().edit(current);
        return "View";
    }

    public String suspendSO() {
        current.setStatus(SalesOrderStatus.Suspended);
        getFacade().edit(current);
        getFacade().scheduleTimer(6000, current.getId());
        return "View";
    }

    public String resumeSO() {
        current.setStatus(SalesOrderStatus.Confirmed);
        getFacade().cancelTimer();
        getFacade().edit(current);
        return "View";
    }

    public String completeSO() {
        salesOrderCompleted(current);
        return "View";
    }
    
    public void salesOrderCompleted(SalesOrderEntity salesOrder) {
        getFacade().markSalesOrderAsCompleted(salesOrder);
    }

    public boolean resumeButton() {
        if (current.getStatus() == SalesOrderStatus.Suspended && checkSystemUser()) {
            return true;
        } else {
            return false;
        }
    }

    private void cancelAllReservations() {
        current.getPlannedReservation().removeAll(current.getPlannedReservation());
        current.getReservations().removeAll(current.getReservations());
    }
    
    public boolean completedButton() {
        if (current.getStatus() != SalesOrderStatus.Completed && checkSystemUser() && current.getStatus() == SalesOrderStatus.Confirmed) {
            return true;
        } else {
            return false;
        }
    }

    public boolean confirmButton() {
        if (current.getStatus() == SalesOrderStatus.Pending && checkSystemUser() 
                && !(current.getInternalStatus().ordinal()<InternalStatus.ProvideLeadTimePending.ordinal())) {
            return true;
        } else {
            return false;
        }
    }

    public boolean cancelButton() {
        if (current.getStatus() != SalesOrderStatus.Cancelled && current.getStatus() != SalesOrderStatus.Rejected && checkSystemUser() && current.getStatus() != SalesOrderStatus.Completed) {
            return true;
        } else {
            return false;
        }
    }

    public boolean suspendEditButton() {
        if (current.getStatus() != SalesOrderStatus.Cancelled && current.getStatus() != SalesOrderStatus.Rejected && current.getStatus() != SalesOrderStatus.Suspended && checkSystemUser() && current.getStatus() != SalesOrderStatus.Completed) {
            return true;
        } else {
            return false;
        }
    }
    
    public boolean inventoryMenu() {
        if (current.getInternalStatus()==InternalStatus.ProvideLeadTimePending)
            return true;
        else return false;
    }
    
    public boolean generateShippingOrderButton() {
        return (current.getStatus()==SalesOrderStatus.Confirmed);
    }
    
    public boolean requestForBillingButton() {
        return (current.getActiveIndex()==3 || current.getActiveIndex()==4);
    }

    public String generateShippingOrders() {
        if (!canRegenerateShippingOrders()) {
            JsfUtil.addErrorMessage("Cannot regenerate shipping orders because some have been packed/fulfilled");
            return "/entities/shippingOrderEntity/ListForSO?faces-redirect=true";
        }

        //archive old shipping orders and packing orders
        Collection<ShippingOrderEntity> oldShippingOrders = current.getShippingOrder();
        for (ShippingOrderEntity oldShipping : oldShippingOrders) {
            if (oldShipping.getId() != null) {
                shippingOrderFacade.originalRemove(oldShipping);
            } else {
                oldShipping = null;
            }
        }
        current.setShippingOrder(new ArrayList<ShippingOrderEntity>());

        Collection<ShippingRequestEntity> shippingRequests = current.getPurchaseOrder().getShippingRequests();

        //initialization
        HashMap<Date, HashMap<AddressEntity, Collection<ShippingRequestEntity>>> shippingDateToAddToRequests = new HashMap<Date, HashMap<AddressEntity, Collection<ShippingRequestEntity>>>();
        for (ShippingRequestEntity request : shippingRequests) {
            shippingDateToAddToRequests.put(request.getShippingDate(),
                    new HashMap<AddressEntity, Collection<ShippingRequestEntity>>());
        }

        //populating hashmaps
        for (ShippingRequestEntity request : shippingRequests) {
            HashMap<AddressEntity, Collection<ShippingRequestEntity>> addToRequests = shippingDateToAddToRequests.get(request.getShippingDate());
            Collection<ShippingRequestEntity> requests = addToRequests.get(request.getAddress());
            if (requests == null) {
                requests = new ArrayList<ShippingRequestEntity>();
            }
            requests.add(request);
            addToRequests.put(request.getAddress(), requests);
        }
        
        String shippingOrderIds = " ";
        String packingOrderIds = " ";

        //generate shipping orders etc
        for (Date date : shippingDateToAddToRequests.keySet()) {

            HashMap<AddressEntity, Collection<ShippingRequestEntity>> addToRequests = shippingDateToAddToRequests.get(date);
            System.out.println("Generate Shipping orders for date: " + date.toString() + ": "
                    + addToRequests.values().size());
            for (AddressEntity add : addToRequests.keySet()) {
                System.out.println("Generate Shipping orders for add: " + add.getId() + ": "
                        + addToRequests.get(add).size());

                //create shipping order
                ShippingOrderEntity shippingOrder = new ShippingOrderEntity();
                shippingOrder.setAddress(add);
                shippingOrder.setStatus(ShippingOrderStatus.pending);
                shippingOrder.setDateToShip(date);

                //create packing order
                PackingOrderEntity packingOrder = new PackingOrderEntity();
                packingOrder.setProductToQuantity(addToRequests.get(add));
                packingOrder.setShippingOrder(shippingOrder);
                packingOrder.setStatus(PackingOrderStatus.pending);
                packingOrder.created(getLoginPerson());

                shippingOrder.setPackingOrder(packingOrder);
                shippingOrder.setSalesOrder(current);
                shippingOrder.created(getLoginPerson());
                shippingOrderFacade.create(shippingOrder);

                current.getShippingOrder().add(shippingOrder);
                shippingOrderIds += shippingOrder.getId() + " ";
                packingOrderIds += packingOrder.getId() + " ";

                //link shipping requests to packing order
                for (ShippingRequestEntity sr : addToRequests.get(add)) {
                    sr.setPackingOrder(packingOrder);
                    sr.modified(getLoginPerson());
                    shippingRequestFacade.edit(sr);
                }
            }
        }

        //update sales order
        current.modified(getLoginPerson());
        ejbFacade.edit(current);

        //inform warehouse manager
        DepartmentEntity warehouse = departmentFacade.findDepartmentByName(Department.Warehouse.getName());
        SystemUserEntity warehouseManager = warehouse.getManager();
        String message = "New shipping orders created: " + shippingOrderIds
                + ". And new packing orders created: " + packingOrderIds;
        systemMessageController.getEjbFacade().createAndSendSystemMessage(warehouseManager,
                message, "/entities/shippingOrderEntity/List.xhtml", systemMessageController);

        return "/entities/shippingOrderEntity/ListForSO?faces-redirect=true";
    }

    //only allow regenerate if status of shipping and packing orders are pending.
    public boolean canRegenerateShippingOrders() {
        boolean valid = true;
        Collection<ShippingOrderEntity> oldShippingOrders = current.getShippingOrder();
        for (ShippingOrderEntity oldShipping : oldShippingOrders) {
            if (oldShipping.getStatus() != ShippingOrderStatus.pending
                    || oldShipping.getPackingOrder().getStatus() != PackingOrderStatus.pending) {
                valid = false;
                break;
            }
        }
        return valid;
    }

    public void setCurrent(SalesOrderEntity current) {
        System.out.println("Set sales current" + current.getId());
        this.current = current;
    }

    public SalesOrderEntity getCurrent() {
        return current;
    }

    public boolean needToPerformCreditCheck() {
        return current.getInternalStatus() == InternalStatus.CreditCheckPending;
    }

    public String getStyle() {
        if (current.isCreditCheckPassed() && !needToPerformCreditCheck()) {
            return "color:green";
        } else {
            return "color:red";
        }
    }

    public void performCreditCheck() {
        try {
            System.out.println("perform credit check");
            //check that customer has account assigned
            CustomerAccountEntity account = current.getCustomer().getCustomerAccount();
            if (account == null || account.getId() == null) {
                throw new CustomerAccountDoesNotExistException("Customer " + current.getCustomer().getId() + " has not yet been assigned an account!");
            }

            //in case of re-perform credit check, refund first
            if (current.getCreditPayable() > 0) {
                refundCreditPayable(false);
            }

            //now credit check
            double totalPayable = current.getPurchaseOrder().getTotalPrice();
            if (!(totalPayable > account.getCreditBalance())) {
                current.setCreditPayable(totalPayable);
                current.setCashPayable(0.0);
                current.setInternalStatus(InternalStatus.ProvideLeadTimePending);
                account.setCreditBalance(account.getCreditBalance() - totalPayable);
            } else { //inseficient credit
                current.setCreditPayable(account.getCreditBalance());
                current.setCashPayable(totalPayable - account.getCreditBalance());
                current.setInternalStatus(InternalStatus.CIABillingRequestPending);
                account.setCreditBalance(0);
            }
            account.modified(getLoginPerson());
            customerAccountFacade.edit(account);

            update();
        } catch (CustomerAccountDoesNotExistException ex) {
            JsfUtil.addErrorMessage(ex, ex.getMessage());
        }
    }

    private void refundCreditPayable(boolean showMessage) {
        System.out.println("refund credit payable");
        double refundAmount = current.getCreditPayable();
        CustomerAccountEntity account = current.getCustomer().getCustomerAccount();
        if (account == null || account.getId() == null) {
            return;
        }

        account.setCreditBalance(account.getCreditBalance() + refundAmount);
        current.setCreditPayable(0.0);
        account.modified(getLoginPerson());
        customerAccountFacade.edit(account);

        if (showMessage) {
            JsfUtil.addSuccessMessage("Customer account credit balance refunded. New balance: " + account.getCreditBalance());
        }
    }

    public boolean ciaRefundAvailable() {
        boolean shouldRefund = false;
        double refundAmount = current.getCashPayable();
        if (refundAmount == 0) {
            return shouldRefund;
        }

        if (current.getRefundRequest() != null) {
            return shouldRefund;
        }

        Collection<BillingRequestEntity> billingRequests = current.getBillingRequests();
        if (billingRequests == null) {
            return shouldRefund;
        }

        for (BillingRequestEntity request : billingRequests) {
            if (request.getType() == InvoiceType.cashInAdvance) {
                CustomerInvoiceEntity invoice = request.getInvoice();
                if (invoice != null && invoice.getAmount() == refundAmount && invoice.getStatus() == InvoiceStatus.paid) {
                    shouldRefund = true;
                    break;
                }
            }
        }

        return shouldRefund;
    }

    //only call this method after ciaRefunAvailable is called and returned true
    public void fileForCIARefundRequest() {
        System.out.println("filing CIA refund request");
        double refundAmount = current.getCashPayable();

        RefundRequestEntity refundRequest = new RefundRequestEntity();
        refundRequest.setSalesOrder(current);
        refundRequest.setAmount(refundAmount);
        refundRequest.setStatus(RefundRequestStatus.pending);
        refundRequest.setNote(note);

        refundRequest.created(getLoginPerson());
        refundRequestFacade.create(refundRequest);

        //inform AR manager
        DepartmentEntity accountsReceivable = departmentFacade.findDepartmentByName(Department.AccountsPayable.getName());
        SystemUserEntity accountsReceivableManager = accountsReceivable.getManager();
        String message = "Please process refund request # " + refundRequest.getId()
                + " for Sales Order #" + current.getId();
        systemMessageController.getEjbFacade().createAndSendSystemMessage(accountsReceivableManager,
                message, "/entities/refundRequestEntity/List.xhtml", systemMessageController);

        JsfUtil.addSuccessMessage("Refund request filed. Request ID: # " + refundRequest.getId());
        note = "";
    }

    //when choose to amend SO instead of request for CIA billing to customer
    public void undoCreditCheck() {
        System.out.println("undo credit check");
        refundCreditPayable(false);
        current.setCashPayable(0.0);
        current.setInternalStatus(InternalStatus.CreditCheckPending);
        update();
    }

    public boolean needToRequestForBillingForCIA() {
        return current.getInternalStatus() == InternalStatus.CIABillingRequestPending && current.getCashPayable() > 0;
    }

    public String generateBillingRequestForCIA() {
        System.out.println("generate billing request for CIA");
        if (!needToRequestForBillingForCIA()) {
            return null;
        }

        BillingRequestEntity billingRequest = new BillingRequestEntity();
        billingRequest.setRequestedAmount(current.getCashPayable());
        billingRequest.setSalesOrder(current);
        billingRequest.created(getLoginPerson());
        billingRequestFacade.create(billingRequest);

        current.getBillingRequests().add(billingRequest);
        current.setInternalStatus(InternalStatus.CIABillingConfirmPending);

        //inform AR manager
        DepartmentEntity accountsReceivable = departmentFacade.findDepartmentByName(Department.AccountsReceivable.getName());
        SystemUserEntity accountsReceivableManager = accountsReceivable.getManager();
        String message = "Please issue cash-in-advance invoice to customer " + current.getCustomer().getFullname()
                + " for Sales Order # " + current.getId() + ".";
        systemMessageController.getEjbFacade().createAndSendSystemMessage(accountsReceivableManager,
                message, "/entities/billingRequestEntity/ListCIA.xhtml", systemMessageController);

        JsfUtil.addSuccessMessage("Billing request filed. #" + billingRequest.getId());
        return update();
    }

    public int getReservedNutriBarFruits() {
        reservedNutriBarFruits = 0;
        List<ReservationEntity> reservations = this.getFacade().currentlyReserved(getSelected().getId(), "Classic Nutri Bar (Fruits)");
        for (ReservationEntity reservation : reservations) {
            if (reservation.isArchived() == false) {
                reservedNutriBarFruits = reservedNutriBarFruits + reservation.getQuantity();
            }
        }
        return reservedNutriBarFruits;
    }

    public void setReservedNutriBarFruits(int reservedNutriBarFruits) {
        this.reservedNutriBarFruits = reservedNutriBarFruits;
    }

    public int getReservedNutriBarNuts() {
        reservedNutriBarNuts = 0;
        List<ReservationEntity> reservations = this.getFacade().currentlyReserved(getSelected().getId(), "Classic Nutri Bar (Nuts)");
        for (ReservationEntity reservation : reservations) {
            if (reservation.isArchived() == false) {
                reservedNutriBarNuts = reservedNutriBarNuts + reservation.getQuantity();
            }
        }
        return reservedNutriBarNuts;
    }

    public void setReservedNutriBarNuts(int reservedNutriBarNuts) {
        this.reservedNutriBarNuts = reservedNutriBarNuts;
    }

    public int getReservedPremiumPowerBarFruits() {
        reservedPremiumPowerBarFruits = 0;
        List<ReservationEntity> reservations = this.getFacade().currentlyReserved(getSelected().getId(), "Premium Power Bar (Redcurrant Fruits)");
        for (ReservationEntity reservation : reservations) {
            if (reservation.isArchived() == false) {
                reservedPremiumPowerBarFruits = reservedPremiumPowerBarFruits + reservation.getQuantity();
            }
        }
        return reservedPremiumPowerBarFruits;
    }

    public void setReservedPremiumPowerBarFruits(int reservedPremiumPowerBarFruits) {
        this.reservedPremiumPowerBarFruits = reservedPremiumPowerBarFruits;
    }

    public int getReservedPremiumPowerBarNuts() {
        reservedPremiumPowerBarNuts = 0;
        List<ReservationEntity> reservations = this.getFacade().currentlyReserved(getSelected().getId(), "Premium Power Bar (Chocolate Nuts)");
        for (ReservationEntity reservation : reservations) {
            if (reservation.isArchived() == false) {
                reservedPremiumPowerBarNuts = reservedPremiumPowerBarNuts + reservation.getQuantity();
            }
        }
        return reservedPremiumPowerBarNuts;
    }

    public void setReservedPremiumPowerBarNuts(int reservedPremiumPowerBarNuts) {
        this.reservedPremiumPowerBarNuts = reservedPremiumPowerBarNuts;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }
}
